package logic

import (
	"context"
	"errors"
	"product-user-module/model/cache"
	"product-user-module/model/mysql"
	"product-user-module/pkg"

	"product-user-module/productrpc/internal/svc"
	"product-user-module/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册
func (l *LoginLogic) Login(in *productrpc.LoginRequest) (*productrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Account).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误")
	}

	result1, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if result1 != in.CaptchaCode {
		return nil, errors.New("图形验证码错误")
	}

	var user mysql.User

	if err := user.FirstOrCreate(mysql.DB, in.Account); err != nil {
		user = mysql.User{
			Account:  in.Account,
			Password: pkg.Md5(in.Password),
		}

		if err := user.UserAdd(mysql.DB); err != nil {
			return nil, err
		}
	}

	return &productrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
